<template>
  <QuillEditor ref="quillRef" v-model:content="content" :options="myOptions" contentType="html" />
  <div class="editor_btn">
    <el-button color="#626aef" :dark="false" plain @click="submitContent">确认提交</el-button>
    <el-button color="#626aef" :dark="false" plain @click="clearEditor">清空</el-button>
  </div>
</template>

<script setup lang="ts">
// import { uploadFile } from '@/api/common/index' //引入上传图片的api
import { addfile } from "@/api/serveFile/index"
import Compressor from "compressorjs";
import { QuillEditor, Quill } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
// import '@/styles/quill.font.css'
import "quill-image-uploader/dist/quill.imageUploader.min.css";
import ImageUploader from "quill-image-uploader";
import BlotFormatter from "quill-blot-formatter";
import { ref, reactive, toRaw, watch, nextTick, getCurrentInstance } from "vue";
import { Action, ElMessage, ElMessageBox } from "element-plus";
const { proxy }: any = getCurrentInstance();

const props = withDefaults(
  defineProps<{
    content: any; // 双向绑定值
  }>(),
  {
    content: "", // 双向绑定值
  }
);
//这是ts下的写法，js是数组
const emit = defineEmits<{
  (e: "update:content", val: any): void;
  (e: "submit", val: any): void;
}>();
const content = ref<string>("");
const quillRef = ref<any>(null);

// Quill.register(fontSizeStyle, true)
Quill.register("modules/imageUploader", ImageUploader);
Quill.register("modules/blotFormatter", BlotFormatter);

//富文本配置项，将模块功能一起写入到配置项内，也可以单独配置Modules
const myOptions = reactive({
  modules: {
    toolbar: [
      //自定义toolbar，或者可以通过essential ,minimal ,full ,以及"" 使用默认选项
      [{ align: [] }],
      [{ list: "ordered" }, { list: "bullet" }],
      ["image"],
      [{ direction: "rtl" }],
      [{ color: [] }, { background: [] }],
      [{ size: ["small", false, "large", "huge"] }], // 字体大小
      ["clean"],
    ],
    // 上传图片
    imageUploader: {
      upload: async (file: any) => {
        try {
          const compressedFile: any = await compressImage(file); // 压缩图片
          return new Promise(async (resolve, reject) => {
            const formData: any = new FormData();
            formData.append("file", compressedFile);
            formData.append("fileType", Number(proxy.$gf.gft(file.name).value));
            formData.append("remark", "真棒");
            formData.append("spaceId", "521634973787096064");
            const fileUrl: any = await addfile(formData, {
              spaceId: "521634973787096064",
            }, (val: any) => {
              console.log(`文件---[${file.name}]---上传进度${val}`);
            });
            resolve(
              fileUrl.fileUrl
            );
          });
        } catch (error) {
          console.error("压缩和上传图像时出错:", error);
        }
      },
    },
    // 图片缩放
    blotFormatter: {},
  },
  placeholder: "请输入内容...",
});

// 图片压缩
const compressImage = (file: any) => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      quality: 0.6, // 设置压缩质量
      maxWidth: 400, // 设置图片最大宽度
      maxHeight: 400, // 设置图片最大高度
      success(result: unknown) {
        resolve(result);
      },
      error(error: any) {
        reject(error);
      },
    });
  });
};
//这个监听是为了让内容回显
watch(
  () => props.content,
  (val: any) => {
    //根据父组件传递内容来改变视图
    content.value = val; //用于监听绑定值进行数据回填
  },
  { immediate: true } //监听绑定立即执行
);
//清空内容
const clearEditor = () => {
  //这里改变这个组件的content.value是没用的
  if (
    content.value == "<p><br></p>" ||
    content.value == "" ||
    content.value == null ||
    content.value == undefined
  ) {
    ElMessage({
      type: "info",
      message: "编辑区已经很干净啦~",
    });
    return;
  }
  toRaw(quillRef.value).setHTML("");
  // emit("update:content", "");
  ElMessage({
    type: "success",
    message: `成功清除内容`,
  });
};
//提交内容
const submitContent = () => {
  if (
    content.value == "<p><br></p>" ||
    content.value == "" ||
    content.value == null ||
    content.value == undefined
  ) {
    ElMessageBox.alert("编辑内容不能为空哦", "温馨提示！", {
      confirmButtonText: "知道了",
      callback: (action: Action) => {
        ElMessage({
          type: "info",
          message: `~期待你的佳作哦~`,
        });
      },
    });
    return;
  }
  ElMessageBox.prompt("请为文章编辑一个标题", "辛苦了", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern:
      /^[\u4e00-\u9fa5a-zA-Z0-9][\u4e00-\u9fa5a-zA-Z0-9,，]{0,100}$/,
    inputErrorMessage:
      "注意只能使用数字、字母大小写、中文、中文逗号,英文逗号字符,长度限制1~100！",
  })
    .then(({ value }) => {
      emit("update:content", content.value)
      emit("submit", {
        value,
        call() {//传递给父组件的回调函数，触发清理编辑区
          toRaw(quillRef.value).setHTML("");
          ElMessage({
            type: "success",
            message: `提交成功，等待审核通过!`,
          });
        },
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消命名",
      });
    });
};
</script>
<style lang="scss">
.ql-container {
  height: calc(100% - 62px) !important;
  box-sizing: border-box;
}

.editor_btn {
  position: absolute;
  height: 42px;
  top: 0px;
  right: 0px;
  z-index: 999;
  // background-color: green;
  display: flex;
  align-items: center;
}
</style>
